package handler

import (
	"github.com/gin-gonic/gin"
	"group-chat/pkg"
	"group-chat/pkg/jwt"
	"group-chat/repository"
	"group-chat/request"
	"net/http"
	"path"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "获取图片失败",
			"data": nil,
		})
	}
	ext := path.Ext(file.Filename)
	end := map[string]bool{
		".jpg": true,
		".png": true,
	}
	if !end[ext] {
		c.JSON(http.StatusOK, gin.H{
			"code": 100001,
			"msg":  "图片的格式错误",
			"data": nil,
		})
	}
	dst := "D:\\gocode\\src\\gao3\\zy\\2\\11\\group-chat\\static\\upload\\" + file.Filename
	c.SaveUploadedFile(file, dst)
	go pkg.Upload(dst, file.Filename)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传图片成功",
		"data": pkg.GetUrl(file.Filename),
	})
}

func Login(c *gin.Context) {
	var data request.UserLogin
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "错误",
			"data": nil,
		})
		return
	}
	user, err := repository.LoginUser(data.Mobile, data.Password)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "用户未登录",
			"data": nil,
		})
		return
	}
	conrt := jwt.CustomClaims{
		ID: uint(user.Id),
	}
	token, err := jwt.NewJWT("2209A").CreateToken(conrt)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "获取失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": token,
	})
}

func Article(c *gin.Context) {
	var data request.ArticleAdd
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "错误",
			"data": nil,
		})
		return
	}
	article, err := repository.AddArticle(data.Title, data.Author, data.Counter, data.Type)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "添加失败",
			"data": nil,
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
}
